import { create } from 'zustand'
import { User } from 'src/hooks/useUsers'
import { request } from '../request'

type Profile = {
  code: number,
  message: string,
  data: User
}

interface ProfileState {
  profile: Profile | null,
  profileLoading: boolean,
  fetchProfile: () => Promise<void>,
}

export const useProfile = create<ProfileState>((set) => ({
  profile: null,
  profileLoading: false,
  fetchProfile: async () => {
    set({ profileLoading: true })
    let profile
    try {
      profile = await request.get('/user/profile')
    } catch (e) {
      if (e.code !== undefined) {
        profile = e
      } else {
        throw e
      }
    }
    set({ profileLoading: false, profile })
  },
}))
